<!--  -->
<template>
    <div class="page-container">
        <div class="header-panel">
            <el-form :inline="true" :model="queryParams" class="demo-form-inline">
                <el-form-item label="测站">
                    <StbprpSelect v-model="queryParams.stcd" placeholder="请选择测站"></StbprpSelect>
                </el-form-item>

                <el-form-item label="时间">
                    <el-date-picker v-model="queryParams.tm" type="datetimerange" range-separator="至"
                        start-placeholder="开始日期" end-placeholder="结束日期" format="yyyy-MM-dd HH:mm"
                        value-format="yyyy-MM-dd HH:mm"></el-date-picker>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
                    <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd"
                        v-hasPermi="['sjcx:sksqgcx:add']">新增</el-button>

                    <el-button type="success" plain icon="el-icon-edit" :disabled="single" @click="handleUpdate"
                        v-hasPermi="['sjcx:sksqgcx:edit']">修改</el-button>

                    <el-button type="danger" plain icon="el-icon-delete" :disabled="multiple" @click="handleDelete"
                        v-hasPermi="['sjcx:sksqgcx:remove']">删除</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="context-panel">
            <div class="context-left">
                <div class="chart" id="chart"></div>
            </div>
            <div class="context-right">
                <el-table :data="tableData" stripe style="width: 100%" v-el-table-infinite-scroll="loadMore"
                    v-loading="loading" @selection-change="handleSelectionChange" height="calc(100% - 38px)">
                    <el-table-column type="selection" width="50" align="center" />
                    <el-table-column prop="stcd" align="center" label="测站编码" />
                    <el-table-column prop="tm" align="center" label="时间" />
                    <el-table-column prop="rz" align="center" label="库上水位" />
                    <el-table-column prop="inq" align="center" label="入库流量" />
                </el-table>
                <!-- 底部加载提示 -->
                <div class="load-more" v-if="tableData.length > 0">
                    <span v-if="loading">加载中...</span>
                    <span v-else-if="noMore">没有更多数据了</span>
                    <span v-else>向下滚动加载更多</span>
                </div>
            </div>
        </div>


        <!-- 添加或修改用户配置对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="800px" :close-on-click-modal="false" append-to-body
            @close="dialogClose">
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                <el-row :gutter="20">
                    <!-- 第一行第一列：测站编码 -->
                    <el-col :span="12">
                        <el-form-item label="测站编码" prop="stcd">
                            <StbprpSelect v-model="form.stcd" placeholder="请选择测站" :disabled="isEdit"
                                style="width: 100%;">
                            </StbprpSelect>
                        </el-form-item>
                    </el-col>

                    <!-- 第一行第二列：时间 -->
                    <el-col :span="12">
                        <el-form-item label="时间" prop="tm">
                            <el-date-picker v-model="form.tm" type="datetime" :disabled="isEdit" style="width: 100%;"
                                placeholder="选择时间" format="yyyy-MM-dd HH:mm" value-format="yyyy-MM-dd HH:mm" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <!-- 库上水位 -->
                        <el-form-item label="库上水位" prop="rz">
                            <el-input v-model="form.rz" placeholder="请输入库上水位（单位：m）" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <!-- 入库流量 -->
                        <el-form-item label="入库流量" prop="inq">
                            <el-input v-model="form.inq" placeholder="请输入入库流量（单位：m³/s）" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <!-- 蓄水量 -->
                        <el-form-item label="蓄水量" prop="w">
                            <el-input v-model="form.w" placeholder="请输入蓄水量（单位：10⁶m³）" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <!-- 库下水位 -->
                        <el-form-item label="库下水位" prop="blrz">
                            <el-input v-model="form.blrz" placeholder="请输入库下水位（单位：m）" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <!-- 出库流量 -->
                        <el-form-item label="出库流量" prop="otq">
                            <el-input v-model="form.otq" placeholder="请输入出库流量（单位：m³/s）" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <!-- 库水特征码 -->
                        <el-form-item label="库水特征码" prop="rwchrcd">
                            <el-select v-model="form.rwchrcd" placeholder="请选择" style="width: 100%;" clearable>
                                <el-option v-for="item in rwchrcdOptions" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <!-- 库水水势 -->
                        <el-form-item label="库水水势" prop="rwptn">
                            <el-select v-model="form.rwptn" placeholder="请选择" style="width: 100%;" clearable>
                                <el-option v-for="item in rwptnOptions" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <!-- 入流时投长 -->
                        <el-form-item label="入流时投长" prop="inqdr">
                            <el-input v-model="form.inqdr" placeholder="请输入入流时投长（单位：h，格式如X.X）" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <!-- 测流方法 -->
                        <el-form-item label="测流方法" prop="msqmt">
                            <el-select v-model="form.msqmt" placeholder="请选择" style="width: 100%;" clearable>
                                <el-option v-for="item in msqmtOptions" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>


                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="open = false">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import * as echarts from 'echarts'
import StbprpSelect from '@/components/Select/StbprpSelect'
export default {
    components: { StbprpSelect },
    data() {
        return {
            queryParams: {
                tm: []
            },
            allData: [],
            tableData: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            loading: false,
            page: 0,
            pageSize: 20,
            total: null,
            noMore: false,
            isEdit: false,
            // 表单参数
            form: {

            },
            // 表单校验
            rules: {
                stcd: [
                    { required: true, message: '请选择测站编码', trigger: 'blur' },
                ],
                tm: [
                    { required: true, message: '请选择时间', trigger: 'blur' },
                ],
            },
            rwchrcdOptions: [
                { label: '干涸', value: '1' },
                { label: '断流', value: '2' },
                { label: '流向不定', value: '3' },
                { label: '逆流', value: '4' },
                { label: '起涨', value: '5' },
                { label: '洪峰', value: '6' },
                { label: '水电厂发电流量', value: 'P' }
            ],
            rwptnOptions: [
                { label: '落', value: '4' },
                { label: '涨', value: '5' },
                { label: '平', value: '6' }
            ],
            msqmtOptions: [
                { label: '流速仪', value: '1' },
                { label: '浮标法', value: '2' },
                { label: '声学法', value: '3' },
                { label: 'ADCP', value: '5' },
                { label: '其它方法', value: '9' }
            ]

        }
    },
    computed: {},
    created() { },
    mounted() {
        this.getList()
    },
    methods: {

        getList() {
            const tm = this.queryParams.tm
            const btm = tm && (tm.length > 0 ? tm[0] : null)
            const etm = tm && (tm.length > 1 ? tm[1] : null)
            this.$request({
                method: 'get',
                url: 'baseApi/st_rsvr_r/getList',
                params: {
                    stcd: this.queryParams.stcd,
                    btm: btm,
                    etm: etm
                    // stcd: '11329410',
                    // btm: '2019-03-01 00:00',
                    // etm: '2019-04-01 23:59'
                }
            }).then((res) => {
                if (res.code === 200) {
                    this.allData = res.data
                    this.total = res.data.length
                    this.page = 1
                    const count = Math.min(this.total, this.pageSize);
                    this.tableData = res.data.slice(0, count)
                    this.initChart()
                }
            })
        },
        handleQuery() {
            if (this.queryParams.stcd == null) {
                this.$message({
                    message: '请选择站点',
                    type: 'warning'
                });
                return
            };
            this.tableData = [];
            this.page = 0;
            this.noMore = false;
            this.getList();
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.title = "添加信息";
            this.open = true
        },
        /** 修改按钮操作 */
        async handleUpdate() {
            this.form = { ...this.ids[0] }
            this.isEdit = true;
            this.title = "修改信息";
            this.open = true
        },
        /** 删除按钮操作 */
        handleDelete() {
            var ids;
            if (this.selection.length == 0) {
                ids = [row]
            } else {
                ids = this.selection
            }
            this.$confirm('是否确认删除该条信息？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$request({
                    url: 'baseApi/st_rsvr_r/delete',
                    method: 'post',
                    data: ids
                }
                ).then(res => {
                    this.handleQuery();
                    this.$message({
                        message: '操作成功',
                        type: 'success'
                    });
                })

            }).catch(() => { })
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    let url = ''
                    if (this.isEdit) {
                        url = 'baseApi/st_rsvr_r/update'
                    } else {
                        url = 'baseApi/st_rsvr_r/insert'
                    }
                    this.$request({
                        url: url,
                        method: 'get',
                        params: this.form
                    }).then((res) => {
                        if (res.code === 200) {
                            this.open = false;
                            this.$message({
                                message: '操作成功',
                                type: 'success'
                            });
                            this.handleQuery()
                        }
                    })
                }
            });
        },
        // 加载更多数据
        async loadMore() {
            if (this.loading || this.noMore || this.page === 0) return;

            this.loading = true;
            try {
                await this.simulateRequest();
                const start = this.tableData.length;
                const remainingCount = this.total - start;
                const count = Math.min(this.pageSize, remainingCount);

                if (count <= 0) {
                    this.noMore = true;
                    return;
                }
                var newData = this.allData.slice(start, start + count)
                this.tableData = [...this.tableData, ...newData];

                if (this.tableData.length >= this.total) {
                    this.noMore = true;
                }
            } catch (error) {
                console.error('加载更多数据失败:', error);
                this.$message.error('加载更多数据失败');
            } finally {
                this.loading = false;
            }
        },
        // 模拟请求延迟
        simulateRequest() {
            return new Promise(resolve => setTimeout(resolve, 800));
        },
        initChart() {
            var chartDom = document.getElementById('chart');
            var myChart = echarts.init(chartDom);
            const data = this.allData
            const rz_data = data.map(item => [item.tm, item.rz])
            const inq_data = data.map(item => [item.tm, item.inq])
            const zyMin = Math.floor(Math.min(...data.map(item => item.rz * 10))) / 10
            const zyMax = Math.ceil(Math.max(...data.map(item => item.rz * 10))) / 10
            const qyMin = Math.floor(Math.min(...data.map(item => item.inq * 10))) / 10
            const qyMax = Math.ceil(Math.max(...data.map(item => item.inq * 10))) / 10
            console.log(zyMin, zyMax, qyMin, qyMax)
            var option = {
                title: {
                    text: '水库水情过程线',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        animation: false
                    }
                },
                legend: {
                    // 开启图例
                    show: true,
                    top: '5%', // 距离顶部10%
                },
                grid: {
                    top: '10%',
                    left: '5%',
                    right: '5%',
                    containLabel: true
                },
                toolbox: {
                    feature: {
                        restore: {},
                        saveAsImage: {}
                    }
                },
                dataZoom: [
                    {
                        show: true,
                        realtime: true,
                        start: 0,
                        end: 100,
                        xAxisIndex: [0, 1]
                    }
                ],
                xAxis: [
                    {
                        type: 'category',
                        boundaryGap: false,
                        axisLine: { onZero: true },
                    }
                ],
                yAxis: [
                    {
                        name: '库上水位(m)',
                        type: 'value',
                        axisLabel: {
                            color: '#409EFF'
                        },
                        axisLine: {
                            lineStyle: {
                                color: '#409EFF'
                            }
                        },
                        min: zyMin,
                        max: zyMax
                    },
                    {
                        name: '入库流量(m³/s)',
                        type: 'value',
                        axisLabel: {
                            color: '#2be943'
                        },
                        axisLine: {
                            lineStyle: {
                                color: '#2be943'
                            }
                        },
                        min: qyMin,
                        max: qyMax
                    },
                ],
                series: [
                    {
                        name: '库上水位',
                        type: 'line',
                        data: rz_data,
                        yAxisIndex: 0
                    }, {
                        name: '入库流量',
                        type: 'line',
                        data: inq_data,
                        yAxisIndex: 1
                    }
                ]
            };


            option && myChart.setOption(option);
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection;
            this.single = selection.length != 1;
            this.multiple = !selection.length;
        },
        dialogClose() {
            this.isEdit = false;
            this.$data.form = this.$options.data().form
            this.$refs.form && this.$refs.form.resetFields()
        }
    },
}
</script>
<style lang="scss" scoped>
//@import url(); 引入公共css类样式
.context-panel {
    display: flex;
    flex-direction: row;
    height: calc(100% - 50px);
    width: 100%;

    .context-left {
        flex: 5;
        border: 2px dashed #ddd;
    }

    .context-right {
        margin-left: 5px;
        flex: 3;
        overflow: hidden;
    }

    .chart {
        height: 100%;
        width: 100%;
        padding: 20px;
        box-sizing: border-box;
    }
}

.load-more {
    text-align: center;
    padding: 10px;
    color: #1f4fec;
    font-size: 14px;
    background: #f8f9fa;
    border-top: 1px solid #ebeef5;
}
</style>